package com.rr.learningdemo.flink;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.ExecutionEnvironmentFactory;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * @author RR
 * @date 2021/6/6 17:59
 */
public class WordCountDataSet {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //从txt文件读取数据
        String txtFilePath = "G:\\IDEAProject\\learning-demo\\src\\main\\resources\\WordCount.txt";
        DataSource<String> stringDataSource = env.readTextFile(txtFilePath);

        //批处理用dataSet，流处理用dataStream
        DataSet<Tuple2<String, Integer>> sum = stringDataSource.flatMap(new MyFlatMapper())
                .groupBy(0) //按照tuple2的0号下标分组
                .sum(1);//按照tuple2的1号下标求和

        sum.print();
    }

    //将文本内容按空格，将单词分隔出来，然后按照（word，1）的形式返回
    //这里的flatMapFunction有两个泛型，第一个String，是接收的数据的泛型，后面的Tuple2是我们输出的结果的泛型
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String,Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector){
            String[] words = s.split(" ");
            for (String word : words) {
                collector.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
